/**
 * 
 */
package x10.eventServices.tcp;

import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;

/**
 * @author Denny Sheirer
 * @date   2011
 */
public class TCPConnectionListener extends Thread{
    Logger logger = Logger.getLogger(this.getClass().getName());
    TCPConnectionManager connectionManager;
    int listenPort;
    int maxConnections;

    public TCPConnectionListener(TCPConnectionManager connectionManager, int listenPort, int maxConnections){
	this.connectionManager = connectionManager;
	this.listenPort = listenPort;
	this.maxConnections = maxConnections;
    }
    
    public void run(){

	Socket incomingConnection = null;

	while(true){
	    try {
		ServerSocket server = new ServerSocket(listenPort);

		logger.fine("TCP Connection Listener running on port " + listenPort);
		while (true) {
		    incomingConnection = server.accept();
		    handleConnection(incomingConnection);
		}
	    } catch (BindException e) {
		logger.fine("Unable to bind to port " + listenPort);
	    } catch (IOException e) {
		logger.fine("Unable to instantiate a ServerSocket on port " + listenPort);
	    }
	}
    }
    
    public void handleConnection(Socket socket){
	if(connectionManager.atMaxConnections()){
	    logger.fine("New TCP client connection request - DENIED - at max connections already");
	    try{
		socket.close();
	    } catch (IOException ioe){
		ioe.printStackTrace();
	    }
	} else {
	    logger.fine("New TCP client connection request from IP:" + socket.getInetAddress() + " Port:" + socket.getPort());
	    TCPConnection tcpConnection = new TCPConnection(connectionManager, socket);
	    Thread thread = new Thread(tcpConnection);
	    thread.start();
	    connectionManager.enqueueTCPConnection(tcpConnection);
	}
    }

}
